package com.sx.pipeline.ui.mine


import android.Manifest
import android.annotation.SuppressLint
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.launcher.ARouter
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.permissionx.guolindev.PermissionX
import com.sx.mvvmlibs.base.BaseApp
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseFragment
import com.sx.pipeline.app.config.IdentityType
import com.sx.pipeline.app.config.NewsQuantityType
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.databinding.FragMineBinding
import com.sx.pipeline.repos.http.res.UserInfoVO
import com.sx.pipeline.utils.GlideEngine
import com.sx.pipeline.utils.LocationUtils
import com.sx.pipeline.utils.PermissionHelper
import io.rong.imkit.utils.RouteUtils
import io.rong.imlib.model.Conversation


/**
 * @Author: YY
 * @Date: 2022/3/7
 * @Description: 我的
 */
class MineFragment : CYDataBindingBaseFragment<FragMineBinding, MineVM>
    (R.layout.frag_mine), View.OnClickListener {

    override fun initIdentity(type: Int) {
        super.initIdentity(type)
        Logs.d("res" + mViewModel.mModel.getToken())
        Logs.d("initIdentity $type")
        when (type) {
            IdentityType.OPERATING_UNIT.code -> {
                // 运营单位
                isShowControls(isWallet = false, isTask = true, isRequire = false, isSupply = false)
            }
            IdentityType.BUILD_UNIT.code -> {
                // 施工单位
                isShowControls(isWallet = true, isTask = true, isRequire = true, isSupply = false, isInvolved = false)
            }
            IdentityType.SUPPLIER.code -> {
                // 供应商
                isShowControls(isWallet = true, isTask = false, isRequire = false, isSupply = true)
                mBinding.sbArea.leftText = "服务区域"
            }
        }
    }

    override fun initListener() {
        // 刷新事件
        mBinding.refreshLayout.setOnRefreshListener {
            mViewModel.updateUserInfo()
            initMap()
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            // 定位
            R.id.tv_city -> {
                // 申请权限
                PermissionHelper.requestTip(context!!,"我们需要知道你的位置方便功能的使用，请授权定位权限",object :PermissionUtils.SimpleCallback{
                    override fun onGranted() {
                        initMap()

                    }

                    override fun onDenied() {
                        ToastUtils.showShort("请授权后再继续操作")
                    }
                },Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS)
//                PermissionX.init(this)
//                    .permissions(
//                        Manifest.permission.ACCESS_FINE_LOCATION,
//                        Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
//                    )
//                    .onExplainRequestReason { scope, deniedList ->
//                        scope.showRequestReasonDialog(
//                            deniedList,
//                            "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                            "确认",
//                            "取消"
//                        )
//                    }
//                    .onForwardToSettings { scope, deniedList ->
//                        scope.showForwardToSettingsDialog(
//                            deniedList,
//                            "您需要手动在“设置”中允许必要的权限",
//                            "确定",
//                            "取消"
//                        )
//                    }
//                    .request { allGranted, grantedList, deniedList ->
//                        if (allGranted) {
//                            // 初始化定位
//                            initMap()
//                        } else {
//                            Toast.makeText(
//                                context,
//                                "这些权限被拒绝,可能影响管建宝正常使用" + ": $deniedList",
//                                Toast.LENGTH_LONG
//                            ).show()
//                        }
//                    }
                // startActivity(Intent(requireContext(), CityPickerActivity::class.java))
            }
            // 我的需求
            R.id.sb_needs -> {
                ARouter.getInstance().build(RoutePath.Mine.OPERATOR_NEEDS_LIST).navigation()
            }
            // 个人资料
            R.id.tv_person_info -> {
                ARouter.getInstance().build(RoutePath.Setting.PROFILE).navigation()
            }
            // 我发布的任务列表
            R.id.tab_release -> RouteManager.Mine.intentToReleaseTaskList()
            // 我参与的任务
            R.id.tab_involved -> RouteManager.Mine.intentToParticipateTaskList()
            // 我参与的任务
            R.id.tab_approve -> RouteManager.Mine.intentToApproveTaskList()
            // 发布任务
            R.id.tab_release_add -> RouteManager.Mine.intentToTaskReleaseAdd()
            // 发布需求
            R.id.tab_requirement_add -> RouteManager.Mine.intentToConstructionNeedsAdd()
            // 我参与的需求
            R.id.tab_involved_needs -> RouteManager.Mine.intentToParticipationNeeds()
            // 我发布的需求
            R.id.tab_release_require -> RouteManager.Mine.intentToReleaseRequire()
            // 我审批的需求
            R.id.tab_approval_require -> RouteManager.Mine.intenttoApprovalRequire()
            // 我发布的供应
            R.id.tab_release_supply -> RouteManager.Mine.intentToReleaseSupply()
            // 发布供应
            R.id.tab_supply_add -> RouteManager.Mine.intentToReleaseSupplyAdd()
            // 我审批的供应
            R.id.tab_approved_supply -> RouteManager.Mine.intentToApprovalSupply()
            // 切换企业
            R.id.tv_switch_business -> {
                ARouter.getInstance().build(RoutePath.Main.SWITCH_BUSINESS).navigation()
            }
            // 钱包余额
            R.id.tv_wallet_txt -> {
                ARouter.getInstance().build(RoutePath.Wallet.BALANCE).navigation()
            }
            // 充值
            R.id.tv_recharge -> ARouter.getInstance().build(RoutePath.Wallet.RECHARGE).navigation()
            // 提现
            R.id.tv_withdraw -> ARouter.getInstance().build(RoutePath.Wallet.WITHDRAW).navigation()
            // 供应商-商品管理
            R.id.sb_commodity_management -> {
                ARouter.getInstance().build(RoutePath.Mine.COMMODITY).navigation()
            }
            // 我的台账
            R.id.sb_ledger -> ARouter.getInstance().build(RoutePath.Mine.LEDGER).navigation()
            //我的服务
            R.id.sb_my_service ->RouteManager.Service.intentToServiceList()
            // 负责区域
            R.id.sb_area -> {
                RouteManager.Territory.intentToTerritoryPage()
            }
            // 我的管线
            R.id.sb_pipeline -> {
                RouteManager.LinePipe.intentToLinePipePage()
            }
            // 意见反馈
            R.id.sb_feedback -> ARouter.getInstance().build(RoutePath.Setting.FEEDBACK).navigation()
            // 联系客服
            R.id.sb_service -> {
//                ARouter.getInstance().build(RoutePath.Setting.CONTACT_SERVICE).navigation()
//                val uri: Uri = Uri.parse("https://web.jiaxincloud.com/onekey.html?id=yzbtyxnuyjvsdg&appName=gxt365&appChannel=20001")
//                val intent = Intent(Intent.ACTION_VIEW, uri)
//                startActivity(intent)
                mViewModel.intentService()
            }
            // 设置
            R.id.sb_setting -> ARouter.getInstance().build(RoutePath.Setting.SETTING).navigation()
            // 身份管理
            R.id.sb_identity -> {
                RouteManager.Main.intentToIdentityManage()
            }
        }
    }

    override fun initData() {
        mBinding.setVariable(BR.onClick, this)
        PermissionHelper.requestTip(context!!,"本App中的地图需要使用定位权限。",object :PermissionUtils.SimpleCallback{
            override fun onGranted() {
                initMap()

            }

            override fun onDenied() {
                ToastUtils.showShort("请授权后再继续操作")
            }
        },Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS)
//        // 申请权限
//        PermissionX.init(this)
//            .permissions(
//                Manifest.permission.ACCESS_FINE_LOCATION,
//                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
//            )
//            .onExplainRequestReason { scope, deniedList ->
//                scope.showRequestReasonDialog(
//                    deniedList,
//                    "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                    "确认",
//                    "取消"
//                )
//            }
//            .onForwardToSettings { scope, deniedList ->
//                scope.showForwardToSettingsDialog(
//                    deniedList,
//                    "您需要手动在“设置”中允许必要的权限",
//                    "确定",
//                    "取消"
//                )
//            }
//            .request { allGranted, grantedList, deniedList ->
//                if (allGranted) {
//                    // 初始化定位
//                    initMap()
//                } else {
//                    Toast.makeText(
//                        context,
//                        "这些权限被拒绝,可能影响管建宝正常使用" + ": $deniedList",
//                        Toast.LENGTH_LONG
//                    ).show()
//                }
//            }
    }

    override fun onResume() {
        super.onResume()
        // 加载缓存数据 过期则刷新加载
        mViewModel.loadData()
        mViewModel.updateUserInfo()
    }

    override fun initViewObservable() {
        super.initViewObservable()
        // 刷新
        observe(mViewModel.mUI.initRefreshEvent()) {
            mBinding.refreshLayout.finishRefresh(it!!)
        }
        // 更新用户数据
        observe(mViewModel.userInfoDataEvent) {
            updateUserInfo(it!!)
            mViewModel.mModel.setPayWord(it.existPayPassword)
        }


        observe(mViewModel.imId){
            RouteUtils.routeToConversationActivity(
                context,
                Conversation.ConversationType.PRIVATE,
                it.toString()
            );
        }

    }

    /**
     * 身份管理
     */
    private fun showIdentityManage() {

    }

    /**
     * 显示不同身份的控件
     */
    private fun isShowControls(
        isWallet: Boolean,
        isTask: Boolean,
        isRequire: Boolean,
        isSupply: Boolean,
        isInvolved: Boolean=true
    ) {
        // 钱包
        mBinding.tabWallet.visibility = if (isWallet) View.VISIBLE else View.GONE
        // 我的任务
        mBinding.tabTask.visibility = if (isTask) View.VISIBLE else View.GONE
        // 我的需求
        mBinding.tabRequire.visibility = if (isRequire) View.VISIBLE else View.GONE
        // 我的供应
        mBinding.tabSupply.visibility = if (isSupply) View.VISIBLE else View.GONE

        // 我的需求
        mBinding.sbNeeds.visibility = if (isTask && !isRequire && !isSupply) View.VISIBLE else View.GONE
        // 我的管线
        mBinding.sbPipeline.visibility = if (isTask) View.VISIBLE else View.GONE
        // 我的台账
        mBinding.sbLedger.visibility = if (isRequire) View.VISIBLE else View.GONE
        // 我的服务
        mBinding.sbMyService.visibility = if (isSupply) View.VISIBLE else View.GONE
        // 商品管理
        mBinding.sbCommodityManagement.visibility = if (isSupply) View.VISIBLE else View.GONE
        mBinding.tabInvolved.visibility = if(isInvolved) View.VISIBLE else View.GONE
    }

    /**
     * 更新数据
     */
    @SuppressLint("SetTextI18n")
    private fun updateUserInfo(info: UserInfoVO) {
        // 头像
        if (!TextUtils.isEmpty(info.avatar)) {
            GlideEngine.createGlideEngine().loadImage(
                requireContext(), info.avatar, mBinding.ivHead
            )
        }
        // 昵称或手机号
        if (!TextUtils.isEmpty(info.userName)) {
            mBinding.tvNick.text = "${info.userName}"
        } else {
            mBinding.tvNick.text = info.phone
        }
        // 单位信息 (暂时显示身份信息)、角标信息
        mBinding.tvLevel.text = when (info.identity) {
            0 -> {
                "${info.unitName} " + IdentityType.OPERATING_UNIT.flag
            }
            1 -> {
                "${info.unitName} " + IdentityType.BUILD_UNIT.flag
            }
            else -> {
                "${info.unitName} " + IdentityType.SUPPLIER.flag
            }
        }

        // 身份管理
        if (info.admin) {
            mBinding.sbIdentity.visibility = View.VISIBLE
        } else {
            mBinding.sbIdentity.visibility = View.GONE
        }

        // 更新角标信息
        updateNewsQuantity(info.newsQuantityMap ?: HashMap<String, Int>())

        //钱包余额
        mBinding.tvBalance.text=info.currencyBalance
    }

    /**
     * 更新角标信息
     */
    private fun updateNewsQuantity(newsMap: HashMap<String, Int>) {

        // 任务-我发布的
        if (newsMap[NewsQuantityType.TASK_PUBLISHED.code] != null) {
            mBinding.tvReleaseNum.text = newsMap[NewsQuantityType.TASK_PUBLISHED.code].toString()
            mBinding.tvReleaseNum.visibility = View.VISIBLE
        } else {
            mBinding.tvReleaseNum.visibility = View.GONE
        }

        // 任务-我参与的
        if (newsMap[NewsQuantityType.TASK_INVOLVED.code] != null) {
            mBinding.tvInvolvedNum.text = newsMap[NewsQuantityType.TASK_INVOLVED.code].toString()
            mBinding.tvInvolvedNum.visibility = View.VISIBLE
        } else {
            mBinding.tvInvolvedNum.visibility = View.GONE
        }

        // 任务-我审批的
        if (newsMap[NewsQuantityType.TASK_APPROVED.code] != null) {
            mBinding.tvApprovedNum.text = newsMap[NewsQuantityType.TASK_APPROVED.code].toString()
            mBinding.tvApprovedNum.visibility = View.VISIBLE
        } else {
            mBinding.tvApprovedNum.visibility = View.GONE
        }

        // 需求-我发布的
        if (newsMap[NewsQuantityType.NEEDS_PUBLISHED.code] != null) {
            mBinding.tvReleaseNeedsNum.text =
                newsMap[NewsQuantityType.NEEDS_PUBLISHED.code].toString()
            mBinding.tvReleaseNeedsNum.visibility = View.VISIBLE
        } else {
            mBinding.tvReleaseNeedsNum.visibility = View.GONE
        }

        // 需求-我参与的
        if (newsMap[NewsQuantityType.NEEDS_INVOLVED.code] != null) {
            mBinding.tvInvolvedNeedsNum.text =
                newsMap[NewsQuantityType.NEEDS_INVOLVED.code].toString()
            mBinding.tvInvolvedNeedsNum.visibility = View.VISIBLE
        } else {
            mBinding.tvInvolvedNeedsNum.visibility = View.GONE
        }

        // 需求-我审批的
        if (newsMap[NewsQuantityType.NEEDS_APPROVED.code] != null) {
            mBinding.tvApprovedNeedsNum.text =
                newsMap[NewsQuantityType.NEEDS_APPROVED.code].toString()
            mBinding.tvApprovedNeedsNum.visibility = View.VISIBLE
        } else {
            mBinding.tvApprovedNeedsNum.visibility = View.GONE
        }

        // 供应-我发布的
        if (newsMap[NewsQuantityType.SUPPLY_PUBLISHED.code] != null) {
            mBinding.tvReleaseApproveNum.text =
                newsMap[NewsQuantityType.SUPPLY_PUBLISHED.code].toString()
            mBinding.tvReleaseApproveNum.visibility = View.VISIBLE
        } else {
            mBinding.tvReleaseApproveNum.visibility = View.GONE
        }

        // 供应-我审批的
        if (newsMap[NewsQuantityType.SUPPLY_APPROVED.code] != null) {
            mBinding.tvApproveInvolvedNum.text =
                newsMap[NewsQuantityType.SUPPLY_APPROVED.code].toString()
            mBinding.tvApproveInvolvedNum.visibility = View.VISIBLE
        } else {
            mBinding.tvApproveInvolvedNum.visibility = View.GONE
        }
    }


    private var mLocationClient: AMapLocationClient? = null
    private fun initMap() {
        try {
            mLocationClient = AMapLocationClient(context)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        if (null != mLocationClient) {
            mLocationClient!!.setLocationListener(mLocationListener)
            val mLocationOption = AMapLocationClientOption()
            mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Battery_Saving
            mLocationOption.isOnceLocation = true
            mLocationOption.isLocationCacheEnable = false
            mLocationClient!!.setLocationOption(mLocationOption)
            mLocationClient!!.startLocation()
        }
    }

    private val mLocationListener =
        AMapLocationListener { aMapLocation: AMapLocation? ->
            if (aMapLocation != null) {
                if (aMapLocation.errorCode == 0) {
                    // 城市名
                    val cityName = aMapLocation.city
                    // 可根据城市的 adcode获取相应城市的天气情况
                    val cityAdCode = aMapLocation.adCode
                    mBinding.tvCity.text = cityName
//                    Log.d(TAG, "onLocationChanged: city: $cityName adCode: $cityAdCode")
                } else {
                    // 定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e(
                        "AMapError", "location Error, ErrCode:"
                                + aMapLocation.errorCode + ", errInfo:"
                                + aMapLocation.errorInfo
                    )
                }
            }
        }

    override fun onDestroy() {
        super.onDestroy()
        if (mLocationClient!=null){
            mLocationClient?.stopLocation()
        }
    }
}